package handlers

import (
	"flag"
	"fmt"
	"reflect"
	"strings"

	"github.com/fsnotify/fsnotify"
	"github.com/liyaozong/mengo/core/base/interfaces"
	"github.com/spf13/viper"
)

type ConfigServer struct {
	v *viper.Viper
}

func NewConfigServer(v *viper.Viper) *ConfigServer {
	// 配置环境变量读取，格式为：XXX_XX
	v.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	v.SetEnvKeyReplacer(replacer)

	var config string
	flag.StringVar(&config, "c", "", "choose config file.")
	flag.Parse()
	if config == "" {
		config = "res/config.yaml"
	}

	v.AddConfigPath(".")
	v.SetConfigType("yaml")
	v.SetConfigFile(config)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	v.WatchConfig()

	return &ConfigServer{
		v: v,
	}
}

func (c *ConfigServer) LoadConfig(typ reflect.Type) interfaces.Configuration {
	config := reflect.New(typ).Interface()
	if err := c.v.Unmarshal(&config); err != nil {
		fmt.Println(err)
	}

	c.v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.String())
		if err := c.v.Unmarshal(&config); err != nil {
			fmt.Println(err)
		}
	})
	return config.(interfaces.Configuration)
}
